<?php
namespace app\api\model;

use app\common\helper\Obj2Array;
use app\common\model\project_model\ButtonModel as Button;
use think\Model;

class ButtonModel extends Button {

    /**
     * 用于接口调用时按参数返回对应的按钮
     * @param null $fields
     * @param null $type
     * @param null array $key
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getButton($fields = null, $type = null, $key = null) {
        $model = new self();
        $field = ['name','type', 'applet_app_id', 'applet_path', 'image_url', 'link'];
        if ($fields) {
            $field = $fields;
        }
        $where['id'] = ['>', 0];
        if ($type) {
            $where['type'] = $type;
        }
        if ($key) {
            if (is_array($key)) {
                $where["key"] = ['IN', $key];
            } else {
                $where['key'] = $key;
            }
        }
        $buttonList = $model->field($field)->where($where)->where(['status' => self::STATUS_OK])->select();
        if (empty($buttonList)) {
            return [];
        }
        return Obj2Array::resObject2Array($buttonList);
    }

    /**
     *
     * 通过key获取一条按钮
     * @param null $field
     * @param null $key
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getOneByKey($key, $field = null) {
        $model = new self();
        $field = $field?$field:['name','type', 'applet_app_id', 'applet_path', 'image_url', 'link', 'status'];
        if (!$key) {
            return false;
        }

        $where['key'] = $key;
        $button = $model->field($field)->where($where)->find();
        return $button;
    }

    /**
     * 通过按钮分组查找出所有该组下的按钮
     * @param $group_name
     * @param null $field
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getButtonByGroup($group_name, $field = null) {
        $model = new self();
        $field = $field?$field:['name','type', 'applet_app_id', 'applet_path', 'image_url', 'link'];
        if (!$group_name) {
            return false;
        }

        $where['group_name'] = $group_name;
        $button_list = $model->field($field)->where(['status' => self::STATUS_OK])->where($where)->select();
        if (!empty($button_list)) {
            return Obj2Array::resObject2Array($button_list);
        }
    }
}